package com.xukehong.demo.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.xukehong.demo.config.AliPayConfig;
import com.xukehong.demo.constant.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Map;

/**
 * @Author: xkh
 * @Date: 2019/4/3 17:43
 * @Version 1.0
 */
@Controller
@RequestMapping("/alipay")
@Api(tags = "支付宝接口")
@Slf4j
public class AliPayController {


    /**
     * 获取会员信息
     */
    @RequestMapping("/gainUserInfo")
    public String gainUserInfo() {
        log.info("开始获取支付宝会员信息");
        //花生壳生成的域名
        String return_url = Constants.BASE_URL + "/alipay/userInfo";
        log.info(return_url);
        String redirectUrl = AliPayConfig.ALIPAY_URL + "?app_id=" + AliPayConfig.APP_ID + "&scope=auth_base&redirect_uri=" + return_url + "&state=123456";
        log.info("获取会员信息链接:" + redirectUrl);
        return "redirect:" + redirectUrl;
    }

    /**
     * 接收会员信息
     */
    @RequestMapping("/userInfo")
    @ResponseBody
    public void userInfo(HttpServletRequest request) {
        Map<String, String[]> map = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            System.out.println("key = " + entry.getKey() + ",Value = " + Arrays.toString(entry.getValue()));
        }
    }

    @GetMapping("/h5/test")
    public String pay() {
        return "aliapyH5test";
    }

    /**
     * 支付宝通过订单号唤醒收银台
     */
    @ApiOperation("支付宝通过订单号唤醒收银台")
    @GetMapping("/h5/{orderNo}")
    public String alipayH5(@PathVariable String orderNo, Model model) {
        orderNo = "{\"requestType\":\"SafePay\",\"fromAppUrlScheme\":\"alipays\",\"dataString\":\"h5_route_token=\\\"RZ139X5KQp4LEfCP1mTPIrncQEtSmwmobilecashierRZ13\\\"&is_h5_route=\\\"true\\\"\"";
        model.addAttribute("orderNo", orderNo);
        return "alipayH5";
    }


    /**
     * 现金红包无线支付接口
     */
    @ApiOperation("现金红包无线支付接口")
    @RequestMapping("/cashRedPacketWireless")
    public String cashRedPacketWireless(Model model) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.URL, AliPayConfig.APP_ID, AliPayConfig.APP_PRIVATE_KEY, AliPayConfig.FORMAT, AliPayConfig.CHARSET, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.SIGN_TYPE);
        AlipayFundTransAppPayRequest requestAli = new AlipayFundTransAppPayRequest();
        AlipayFundTransAppPayModel modelAli = new AlipayFundTransAppPayModel();
        //商户端唯一订单号
        modelAli.setOutBizNo(RandomStringUtils.randomNumeric(10));
        //订单总金额
        modelAli.setTransAmount("1");
        //销售产品码 STD_RED_PACKET 现金红包
        modelAli.setProductCode("STD_RED_PACKET");
        //业务场景 PERSONAL_PAY 发红包
        modelAli.setBizScene("PERSONAL_PAY");
        requestAli.setBizModel(modelAli);
        AlipayFundTransAppPayResponse response = alipayClient.pageExecute(requestAli);
        if (response.isSuccess()) {
            log.info("现金红包无线支付接口：" + response.getBody());
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        model.addAttribute("body", response.getBody());
        return "/payment/alipay/body";
    }

    /**
     * 统一转账接口
     *
     * @param model
     * @return
     * @throws AlipayApiException
     */
    @ApiOperation("统一转账接口")
    @RequestMapping("/consolidatedTransfer")
    public String consolidatedTransfer(Model model) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.URL, AliPayConfig.APP_ID, AliPayConfig.APP_PRIVATE_KEY, AliPayConfig.FORMAT, AliPayConfig.CHARSET, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.SIGN_TYPE);
        AlipayFundTransUniTransferRequest requestAli = new AlipayFundTransUniTransferRequest();
        AlipayFundTransUniTransferModel modelAli = new AlipayFundTransUniTransferModel();
        //商户端唯一订单号
        modelAli.setOutBizNo(RandomStringUtils.randomNumeric(10));
        //订单总金额
        modelAli.setTransAmount("1");
        //业务产品码 STD_RED_PACKET 现金红包  TRANS_ACCOUNT_NO_PWD 单笔无密转账
        modelAli.setProductCode("STD_RED_PACKET");
        //业务场景 PERSONAL_COLLECTION：C2C现金红包-领红包   DIRECT_TRANSFER：B2C现金红包、单笔无密转账
        modelAli.setBizScene("PERSONAL_COLLECTION");
        //收款方信息
        Participant participant = new Participant();
        //参与方的唯一标识
        participant.setIdentity("15695916921");
        //参与方的标识类型 ALIPAY_USER_ID 支付宝的会员ID  ALIPAY_LOGON_ID：支付宝登录号，支持邮箱和手机号格式
        participant.setIdentityType("ALIPAY_LOGON_ID");
        //参与方的真实姓名 当identity_type=ALIPAY_LOGON_ID时，本字段必填。
        participant.setName("许克弘");
        modelAli.setPayeeInfo(participant);
        requestAli.setBizModel(modelAli);
        AlipayFundTransUniTransferResponse response = alipayClient.pageExecute(requestAli);
        if (response.isSuccess()) {
            log.info("统一转账接口：" + response.getBody());
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        model.addAttribute("body", response.getBody());
        return "/payment/alipay/body";
    }


    /**
     * alipay.fund.coupon.order.app.pay(红包无线支付接口)
     */
    @ApiOperation("红包无线支付接口")
    @RequestMapping("/redEnvelopeWireless")
    public String redEnvelopeWireless(Model model) throws AlipayApiException, UnsupportedEncodingException {
        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.URL, AliPayConfig.APP_ID, AliPayConfig.APP_PRIVATE_KEY, AliPayConfig.FORMAT, AliPayConfig.CHARSET, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.SIGN_TYPE);
        AlipayFundCouponOrderAppPayRequest requestAli = new AlipayFundCouponOrderAppPayRequest();
        AlipayFundCouponOrderAppPayModel modeAli = new AlipayFundCouponOrderAppPayModel();
        modeAli.setOutOrderNo(RandomStringUtils.randomNumeric(10));
        modeAli.setOutRequestNo(RandomStringUtils.randomNumeric(10));
        modeAli.setOrderTitle("红包");
        modeAli.setAmount("2.00");
        requestAli.setBizModel(modeAli);
        AlipayFundCouponOrderAppPayResponse response = alipayClient.sdkExecute(requestAli);
        if (response.isSuccess()) {
            log.info("红包无线支付接口：" + response.getBody());
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        model.addAttribute("orderNo", response.getBody());
        return "/alipayH5";
    }

    /**
     * alipay.fund.coupon.order.app.pay(test)
     */
    @ApiOperation("test")
    @RequestMapping("/test")
    public String test(Model model) throws AlipayApiException, UnsupportedEncodingException {
        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.URL, AliPayConfig.APP_ID, AliPayConfig.APP_PRIVATE_KEY, AliPayConfig.FORMAT, AliPayConfig.CHARSET, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.SIGN_TYPE);
        AlipayTradeWapPayRequest requestAli = new AlipayTradeWapPayRequest();
        AlipayTradeWapPayModel modelAli = new AlipayTradeWapPayModel();
        modelAli.setSubject("测试");
        modelAli.setOutTradeNo(RandomStringUtils.randomNumeric(10));
//        model.setTimeoutExpress("配置文件：超时时间");
        modelAli.setTotalAmount("1");
//        model.setSellerId("配置文件：支付宝用户ID");
        modelAli.setProductCode("QUICK_WAP_WAY");
        modelAli.setQuitUrl("http://www.baidu.com");
        requestAli.setBizModel(modelAli);
        requestAli.setReturnUrl("http://www.baidu.com");
        requestAli.setNotifyUrl("http://www.baidu.com");
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(requestAli);
        if (response.isSuccess()) {
            log.info("test：" + response.getBody());
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        model.addAttribute("body", response.getBody());
        return "/payment/alipay/body";
    }



    /**
     * alipay.fund.coupon.order.app.pay(test)
     */
    @ApiOperation("test1")
    @RequestMapping("/test1")
    public String test1(Model model) throws AlipayApiException, UnsupportedEncodingException {
        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.URL, AliPayConfig.APP_ID, AliPayConfig.APP_PRIVATE_KEY, AliPayConfig.FORMAT, AliPayConfig.CHARSET, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.SIGN_TYPE);
        AlipayFundCouponOrderPagePayRequest requestAli = new AlipayFundCouponOrderPagePayRequest();
        AlipayFundCouponOrderPagePayModel modelAli = new AlipayFundCouponOrderPagePayModel();
        modelAli.setOutOrderNo(RandomStringUtils.randomNumeric(10));
        modelAli.setOutRequestNo(RandomStringUtils.randomNumeric(10));
        modelAli.setOrderTitle("备注");
        modelAli.setAmount("1");
        requestAli.setBizModel(modelAli);
        AlipayFundCouponOrderPagePayResponse response = alipayClient.execute(requestAli);
        if (response.isSuccess()) {
            log.info("test：" + response.getBody());
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        model.addAttribute("body", response.getBody());
        return "/payment/alipay/body";
    }





}
